#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
//定义读写锁
pthread_rwlock_t rwlock;

int counter=0;

//写者线程
void *write_pthread(void *arg)
{
	//表示几号线程
	int number=(int)arg;
	int tmp=0;
	while(1){
		//写之前先申请锁
		pthread_rwlock_wrlock(&rwlock);
		tmp=counter;
		++counter;
		printf("i am thread %d, old data is %d now is %d\n",number,tmp,counter);	
		
		//释放锁
		pthread_rwlock_unlock(&rwlock);	
		sleep(2);
	}
}

//读者线程
void *read_pthread(void *arg)
{
	int number=(int) arg;
	while(1){
		pthread_rwlock_rdlock(&rwlock);
		printf("i am thread %d,now data is %d\n",number,counter);

		pthread_rwlock_unlock(&rwlock);

		sleep(1);
	}	
}

int main()
{
	int i=0;
	pthread_t tid[8];

	pthread_rwlock_init(&rwlock,NULL);	
	//创建三个写者线程
	for(; i<3;i++){
		pthread_create(tid+1,NULL,write_pthread,(void *)i);
	}
	//创建五个读者线程
	for(;i<5;i++){
		pthread_create(tid+1,NULL,read_pthread,(void *)i);
	}
	for(i=0;i<8;i++){
		pthread_join(tid[i],NULL);
	}
	//销毁读写锁
	pthread_rwlock_destroy(&rwlock);
	return 0;
}











